//
//  PreorderViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/14.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit

class PreorderCarViewController: UITableViewController, SegueHandlerType {

    enum SegueIdentifier: String {
        case locationSegue
        case carSegue
        case preorderPaySegue
        case webSegue
    }
    
    @IBOutlet weak var useTimeField: UITextField!
    
    @IBOutlet var datePicker: UIDatePicker!

    @IBOutlet var toolbar: UIToolbar!
    
    @IBOutlet weak var isAcceptAdjustLabel: UILabel!
    
    @IBOutlet weak var parkingLabel: UILabel!
    
    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var carTypeNameLabel: UILabel!
    
    @IBOutlet weak var preorderDescLabel: UILabel!
    
    private var config: Preorder.Config? {
        didSet {
            if let c = config {
                carTypeNameLabel.text = c.carTypeName
                
                let t = (c.useStartTime + 29 * 60 + 59) / 1800 * 1800
                
                datePicker.minimumDate = Date(timeIntervalSince1970: TimeInterval(t))
                datePicker.maximumDate = Date(timeIntervalSince1970: TimeInterval(c.useEndTime))
                selectedCarTypeId = c.carTypeId
            }
        }
    }
    
    private var isAcceptAdjust = 1
    
    private var selectedParkingCarId: String? = nil
    
    private var selectedLocation: CLLocationCoordinate2D? = nil
    
    private var selectedPreAmount: String = "" {
        didSet {
            amountLabel.text = "下单需支付预约费用\(selectedPreAmount)元"
            amountLabel.isHidden = selectedPreAmount == ""
        }
    }
    
    private var selectedCarTypeId: String? = nil
    
    private var selectedTime: Date?
    
    @IBOutlet weak var amountLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        preorderDescLabel.text = slipViewController?.config?.preorderDesc
        
        useTimeField.inputView = datePicker
        useTimeField.inputAccessoryView = toolbar
        
        loadConfig()
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 1:
            performSegue(.locationSegue, sender: nil)
        case 2:
            break
            //暂不选择车型
//            performSegue(.carSegue, sender: nil)
        case 3:
            showParkingActionSheet()
        case 4:
            showAcceptAdjustActionSheet()
        default:
            break
        }
    }
    
    // MARK: - IBAction
    
    @IBAction func selectedLocation(segue: UIStoryboardSegue) {
        if let vc = segue.source as? SelectLocationViewController {
            addressLabel.text = vc.addressLabel.text
            selectedLocation = vc.location
        }
    }
    
    @IBAction func selectTime(_ sender: UIBarButtonItem) {
        var t = Int(datePicker.date.timeIntervalSince1970)
        t = t / 1800 * 1800
        if let c = config {
            t = c.useStartTime > t ? c.useStartTime : t
            t = c.useEndTime > t ? t : c.useEndTime
        }
        
        selectedTime = Date(timeIntervalSince1970: TimeInterval(t))
        
        useTimeField.text = Date.dateConvertString(date: selectedTime!)
        useTimeField.textColor = UIColor(valueRGB: 0x6c6c8d, alpha: 1.0)
        
        view.endEditing(true)
    }
    
    @IBAction func submit(_ sender: UIButton) {
        
        guard User.isAuthentication() else {
            //先认证
            if let user = User.info() {
                let storyBoard = UIStoryboard(name: "Attestation", bundle: nil)
                switch user.certStep {
                case 0:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "IDCardViewController") as? IDCardViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                case 1:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "DrivingLicenseViewController") as? DrivingLicenseViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                case 2:
                    let vc = storyBoard.instantiateViewController(withIdentifier: "ReviewAttentationSegue")
                    navigationController?.pushViewController(vc, animated: true)
                case 3:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "RejectViewController") as? RejectViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                default:break
                }
            }
            return
        }

        
        guard User.isPaydeposit() || User.memberType() == 3 || User.isBoundCard() else {
            let storyBoard = UIStoryboard(name: "UserInfo", bundle: nil)
            if let vc = storyBoard.instantiateViewController(withIdentifier: "DepositInfoViewController") as? DepositInfoViewController {
            vc.page = .timeRent
            navigationController?.pushViewController(vc, animated: true)
            }
            return
        }

        guard let time = selectedTime?.timeIntervalSince1970 else {
            showError("请选择用车时间")
            return
        }
        
        guard let address = addressLabel.text else {
            showError("请选择地点")
            return
        }
        
        guard let loc = selectedLocation else {
            showError("请选择地点")
            return
        }
        
        guard let id = selectedParkingCarId else {
            showError("请选择停车范围")
            return
        }
        
        guard let carId = selectedCarTypeId else {
            showError("请选择车型")
            return
        }

        JZLoading.showLoadingWith(toView: self.view)
        Preorder.create(useCarTime: Int(time),
                        useCarAddress: address,
                        location: loc,
                        parkingCarId: id,
                        isAcceptAdjust: isAcceptAdjust,
                        carTypeId: carId,
                        success: { [weak self] data in
                            JZLoading.hideLoading()
                            if let data = data {
                                self?.performSegue(.preorderPaySegue, sender: data)
                            }
        }) { msg in
            JZLoading.hideLoading()
            self.showError(msg)
        }
    }
    
    // MARK: - custom method
    
    private func loadConfig() {
        guard let app = UIApplication.shared.delegate as? AppDelegate,
            let loc = app.userLocation else {
                return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Preorder.config(location: loc, success: { config in
            JZLoading.hideLoading()
            self.config = config
        }) { msg in
            JZLoading.hideLoading()
            self.showError(msg)
        }
    }
    
    private func showParkingActionSheet() {
        guard let config = config else {
            return
        }
        
        let sheet = UIAlertController(title: "请选择停车范围",
                                      message: nil,
                                      preferredStyle: .actionSheet)
        
        for i in config.parkingCarData {
            let title = "\(i.parkingDistance)米（需缴纳\(i.preAmount)元预约费用）"
            sheet.addAction(UIAlertAction(title: title, style: .default) { action in
                self.selectedParkingCarId = i.parkingCarId
                self.selectedPreAmount = i.preAmount
                self.parkingLabel.text = "\(i.parkingDistance)米"
                self.parkingLabel.textColor = UIColor(valueRGB: 0x6c6c8d, alpha: 1.0)
            })
        }
        
        sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        present(sheet, animated: true)
    }
    
    private func showAcceptAdjustActionSheet() {
        let sheet = UIAlertController(title: "停车范围内无车位是否接受调剂到超出范围",
                                      message: nil,
                                      preferredStyle: .actionSheet)
        sheet.addAction(UIAlertAction(title: "是", style: .default) { action in
            self.isAcceptAdjust = 1
            self.isAcceptAdjustLabel.text = "是"
        })
        sheet.addAction(UIAlertAction(title: "否（可能预约失败）", style: .default) { action in
            self.isAcceptAdjust = 0
            self.isAcceptAdjustLabel.text = "否"
        })
        
        sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        present(sheet, animated: true)
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segueIdentifier(forSegue: segue) {
        case .locationSegue:
            break
        case .carSegue:
            break
        case .preorderPaySegue:
            if let vc = segue.destination as? PreorderPayViewController {
                vc.name = config?.carTypeName
                vc.address = addressLabel.text
                vc.useCarTime = datePicker.date.timeIntervalSince1970
                vc.createData = sender as? Preorder.Create
            }
        case .webSegue:
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.preorderRule)
            }
        }
    }

}
